import os
import time
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import yaml
from recognizer.recognizer import video_processor
from upload.upload import output_csv, upload_video
from upload.upload import upload_video
from common.file_utils import output_video_dir, output_in_video_dir
from spotter.spot_key_frame import extract_keyframes
from concurrent.futures import ThreadPoolExecutor
from datahub import video_queues
# from recognizer_car_num.detect_plate import recognize_car_num
from flask_socketio import SocketIO
import upload

app = Flask(__name__)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins="*")

executor = ThreadPoolExecutor(max_workers=4)

with open('config.yml', 'r') as f:
    config = yaml.safe_load(f)

@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/upload', methods=['POST'])
def get_upload_video():
    # 获取上传的文件
    if 'file' not in request.files:
        raise Exception('No file uploaded')
    file = request.files['file']
    new_file_name = upload_video(file)
    response = {
        'success': True,
        'filename': new_file_name
    }
    return jsonify(response), 200


@app.route('/spot_key_frame', methods=['GET'])
def remove_static_frame():
    try:
        filename = request.args.get('filename')
        if not filename:
            raise Exception('filename is empty')
    except Exception as e:
        raise Exception('invalid params:' + str(e))

    out_video_path = extract_keyframes(filename)
    data = {
        'output_video': out_video_path
    }
    return jsonify(data), 200


@app.route('/recognize', methods=['POST'])
def recognize_video():
    # 获取请求中的 JSON 数据
    data = request.json
    # 检查是否包含 'type' 和 'filename' 字段
    if 'value' in data and 'filename' in data:
        target_type = int(data['value'])
        filename = data['filename']
        # 创建一个进度队列
        if filename not in video_queues:
            video_queues[filename] = []
        # 启动新线程执行视频处理
        # 人、车、动物识别
        executor.submit(video_processor, filename, target_type, socketio)
        response = {
            'success': True,
        }
        return jsonify(response), 200
        # else:
        #     #车牌识别
        #     socketio.emit('log_message', {'data': 'carNum recognize'})
        #     executor.submit(recognize_car_num,data['car_num'],filename)
        #     response = {
        #         'success': True,
        #     }
        # return jsonify(response), 200
    else:
        response = {
            'success': False,
            'message': 'No fileName OR No targetType'
        }
        return jsonify(response), 200


@app.route('/progress/<string:filename>', methods=['GET'])
def get_progress(filename):
    if filename in video_queues:
        if len(video_queues[filename]) > 0:
            progress = video_queues[filename][len(video_queues[filename])-1]
        else:
            progress = 0
        response = {
            'progress': progress
        }
        if progress == 100:
            response = {
                'progress': progress,
                'output_video': output_video_dir(filename)
            }
            del video_queues[filename]

    else:
        response = {
            'progress': 0  # 未找到用户的队列
        }
    return jsonify(response)


@app.route('/download/<string:filename>', methods=['GET'])
def download_video(filename):
    video_path = config['output_video_dir']+filename
    # try:
    return send_file(video_path, as_attachment=True)
    # except Exception as e:
    #     return str(e), 500
    
# 获取下载文件列表
@app.route('/downlist/<string:filename>')
def getDownList(filename):
    output_in_video = output_in_video_dir(filename)
    output_video = output_video_dir(filename)
    output_csvN = output_csv(filename)
    result_table_data = []
    
    result_table_data.append(get_file_info(output_in_video))
    result_table_data.append(get_file_info(output_video))
    result_table_data.append(get_file_info(output_csvN))
    
    print(result_table_data)
    return jsonify(result_table_data)

# 启动WebSocket连接
@socketio.on('connect')
def handle_connect():
    print('Client connected')

# 关闭WebSocket连接
@socketio.on('disconnect')
def handle_disconnect():
    print('Client disconnected')
    
#获取文件信息   
def get_file_info(file_path):
    # Get file information using os.path
    file_stat = os.stat(file_path)
    file_name = os.path.basename(file_path)
    # Convert modification time to a readable format
    modification_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(file_stat.st_mtime))

    # Convert file size to KB, MB, or GB
    size = file_stat.st_size
    if size < 1048576:
        size_str = '{:.2f} KB'.format(size / 1024)
    elif size < 1073741824:
        size_str = '{:.2f} MB'.format(size / 1048576)
    else:
        size_str = '{:.2f} GB'.format(size / 1073741824)
        
    return {
        'name': file_name,
        'time': modification_time,
        'size': size_str,
    }

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000)
